from django.db import models
from django.contrib.auth.models import User
from django.urls import  reverse

# Create your models here.

class Category(models.Model):
    """
    分类
    """
    name = models.CharField('分类名称',max_length=10)
    desc = models.CharField("描述",max_length=30,null=True,blank=True)

    class Meta:
        verbose_name = "文章分类"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name



class Tag(models.Model):
    name = models.CharField(max_length=20)

    class Meta:
        verbose_name = "标签名称"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

class Article(models.Model):
    """
    文章
    """
    author = models.ForeignKey(User,verbose_name="作者",on_delete=models.DO_NOTHING)
    title = models.CharField('文章标题',max_length=50,)
    content = models.TextField('文章内容')
    tags = models.ManyToManyField(Tag,verbose_name="标签",default='')
    counter = models.PositiveIntegerField(default=0,verbose_name='访问数')
    category = models.ForeignKey(Category,verbose_name='文章分类',on_delete=models.DO_NOTHING)
    created_time = models.DateTimeField('创建时间',auto_now_add=True)   # 当该对象第一次被创建是自动设置该字段为现在日期，创建日期。
    updated_time = models.DateTimeField('修改时间',auto_now=True)   # 保存时自动设置该字段为现在日期，最后修改日期

    class Meta:
        # ordering 指定模型返回的数据的排列顺序
        # '-created' 表明数据应该以倒序排列
        ordering = ("-created_time",)
        verbose_name = "文章"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title

    # 统计浏览量
    def increase_views(self):
        self.counter += 1
        self.save(update_fields=['counter'])


    # def save(self,*args,**kwargs):
    #
    #     super().save(*args,**kwargs)

    # 生成url
    def get_abstruct_url(self):
        return reverse("article:article_detail",kwargs={"id":self.pk})
